package service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import common.ServerResponse;
import domain.product;
import domain.shoppingcart;
import service.IShoppingcartService;
import util.bigDecimalUtil;
import util.jdbcUtil;
import vo.CartProductVO;
import vo.CartVO;

public class ShoppingcartServiceImpl implements IShoppingcartService {
	
	
	/********5.1购物车list**********/
	public ServerResponse list(Object obj_session_user_id) {
		// TODO Auto-generated method stub
		//登录判断
		if(obj_session_user_id==null) {
			return ServerResponse.serverResponseByError("用户未登录");
		}
		System.out.println("ok:用户ID不为空,可以继续操作");
		Long user_id=(Long)obj_session_user_id;
		//Long user_id=(long)1;
		return ServerResponse.serverResponseBySuccess(getCartVO(user_id));
	}
	
	
	/********5.2购物车add**********/
	public ServerResponse add(String str_product_id,String str_count,Object obj_session_user_id) {
		// TODO Auto-generated method stub
		//登录判断
		if(obj_session_user_id==null) {
			return ServerResponse.serverResponseByError("用户未登录");
		}
		Long user_id = (Long) obj_session_user_id;
		//Long user_id=(long)1;
		//1.参数非空校验
		if(str_product_id==null||str_count==null) {
			return ServerResponse.serverResponseByError("参数不能为空");
		}
		//2.根据product_id和user_id查询购物信息
		//sql语句
		String sql1="select * from shoppingcart where user_id = ? and product_id = ?";
		String sql2="insert into shoppingcart(user_id,product_id,quantity,checked,create_time) values (?,?,?,?,?)";
		String sql3="update shoppingcart set id=?,user_id=?,product_id=?,quantity=?,checked=? update_time=? where id = ?";
		List<shoppingcart> shoppingcart = jdbcUtil.select(shoppingcart.class, sql1, user_id,str_product_id);
		Long product_id = Long.parseLong(str_product_id);
		Long count = Long.parseLong(str_count);
		Long checked =(long)1;
		//生成现在的时间
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time=sdf.format(date);
		if(shoppingcart.size()==0) {
			//新增（添加）购物车
			int i = jdbcUtil.update(sql2, user_id,product_id,count,checked,time);
			if(i==0) {
				return ServerResponse.serverResponseByError("添加购物车失败");
			}else {
				return ServerResponse.serverResponseBySuccess(getCartVO(user_id),"添加购物车成功");
			}
		}else {
			//更新购物车
			int i = jdbcUtil.update(sql3,shoppingcart.get(0).getId(),user_id,product_id,count,checked,time);
			if(i==0) {
				return ServerResponse.serverResponseByError("更新购物车失败");
			}else {
				return ServerResponse.serverResponseBySuccess(getCartVO(user_id), "更新购物车成功");
			}
		}
	}
	
	
	/********5.3更新购物车某个商品数量**********/
	public ServerResponse update(String str_product_id,String str_count,Object obj_session_user_id) {
		// TODO Auto-generated method stub
		//登录判断
		if(obj_session_user_id==null) {
			return ServerResponse.serverResponseByError("用户未登录");
		}
		Long user_id=(Long)obj_session_user_id;
		
		//1.参数非空判断
		if(str_product_id==null||str_count==null) {
			return ServerResponse.serverResponseByError("参数不能为空");
		}
		//2.查询购物车中商品
		//sql语句
		String sql1="select * from shoppingcart where user_id = ? and product_id = ?";
		String sql2="update shoppingcart set quantity=? where product_id=?";
		List<shoppingcart> shoppingcart = jdbcUtil.select(shoppingcart.class, sql1, user_id,str_product_id);
		Long product_id = Long.parseLong(str_product_id);
		Long count = Long.parseLong(str_count);
		if(shoppingcart.size()>0) {
			//3.购物车有商品，更新数量
			shoppingcart.get(0).setQuantity(count);
			int i =jdbcUtil.update(sql2, count,product_id);
			//4.返回CartVO
			if(i==0) {
				return ServerResponse.serverResponseByError("更新购物车失败");
			}else {
				return ServerResponse.serverResponseBySuccess(getCartVO(user_id), "更新购物车成功");
			}
		}else {
			return ServerResponse.serverResponseByError("购物车无商品");
		}
		
		
		
	}
	
	//移除购物车某个产品
		public ServerResponse delete_product(String product_id, Object obj_session_user_id) {
			
			if(obj_session_user_id==null) {
				return ServerResponse.serverResponseByError("用户未登录");
			}
			Long user_id = (Long) obj_session_user_id;
		
			String sql="select * from shoppingcart where product_id=? and user_id=?";
			List<shoppingcart> l=jdbcUtil.select(shoppingcart.class, sql, product_id,user_id);
			System.out.print("此时的l是："+l);
			if(l.size()>0) {
				
				String sql1="delete from shoppingcart where product_id=? and user_id=?";
				int i=jdbcUtil.update(sql1,product_id,user_id);
				if(i>0) {
					return ServerResponse.serverResponseBySuccess(getCartVO(user_id));
				}else {
					return ServerResponse.serverResponseByError("删除失败，未找到该购物车信息");
				}
			}
			else {
				return ServerResponse.serverResponseByError("删除失败，外面失败");
			}
		}

		//购物车取消选中某个商品
		public ServerResponse un_select(String product_id, Object obj_session_user_id) {
			if(obj_session_user_id==null) {
				return ServerResponse.serverResponseByError("用户未登录");
			}
			Long user_id =Long.parseLong(obj_session_user_id.toString());
			
			String sql="select * from shoppingcart where product_id=? and user_id=?";
			List<shoppingcart> l=jdbcUtil.select(shoppingcart.class, sql, product_id,user_id);
			if(l.size()>0) {
				
				String sql1="update shoppingcart set checked=? where product_id=? and user_id=?";
				int i=jdbcUtil.update(sql1,"0",product_id,user_id);
				if(i>0) {
					return ServerResponse.serverResponseBySuccess(getCartVO(user_id));
				}else {
					return ServerResponse.serverResponseByError("💩");
				}
			}
			else {
				return ServerResponse.serverResponseByError("💩");
			}
		}

		//购物车选中某个商品
		public ServerResponse select(String product_id, Object obj_session_user_id) {
			if(obj_session_user_id==null) {
				return ServerResponse.serverResponseByError("用户未登录");
			}
			Long user_id = (Long) obj_session_user_id;
			
			String sql="select * from shoppingcart where product_id=? and user_id=?";
			List<shoppingcart> l=jdbcUtil.select(shoppingcart.class, sql, product_id,user_id);
			if(l.size()>0) {
				
				String sql1="update shoppingcart set checked=? where product_id=? and user_id=?";
				int i=jdbcUtil.update(sql1,"1",product_id,user_id);
				if(i>0) {
					return ServerResponse.serverResponseBySuccess(getCartVO(user_id));
				}else {
					return ServerResponse.serverResponseByError("💩");
				}
			}
			else {
				return ServerResponse.serverResponseByError("💩");
			}
		}
	
	
	/***获取CartVO***/
	private CartVO getCartVO(Long user_id) {
		CartVO cartVO = new CartVO();
		//1.根据user_id查询购物信息——>List<shoppingcart>
		//sql语句
		String sql1="select * from shoppingcart where user_id=?";
		String sql2="select * from product where id=?";
		String sql3="update shoppingcart set quantity=? where id=?";
		String sql4="select * from shoppingcart where user_id=? and checked=0";
		List<shoppingcart> cartList = jdbcUtil.select(shoppingcart.class, sql1, user_id);
		//2.List<shoppingcart>——>List<CartProductVO>
		List<CartProductVO> cartProductVOList = new ArrayList<CartProductVO>();
		
		//购物车总价格
		BigDecimal cartTotalPrice = new BigDecimal("0");
		
		if(cartList.size()>0) {
			//遍历cartList
			for(shoppingcart cart:cartList) {
				CartProductVO cartProductVO = new CartProductVO();
				cartProductVO.setId(cart.getId());
				cartProductVO.setQuantity(cart.getQuantity());
				cartProductVO.setUser_id(user_id);
				cartProductVO.setChecked(cart.getChecked());
				//查询商品
				List<product> products = jdbcUtil.select(product.class, sql2, cart.getProduct_id());
				if(products.size()>0) {
					cartProductVO.setProduct_id(cart.getProduct_id());
					cartProductVO.setMain_image(products.get(0).getMain_image());
					cartProductVO.setProduct_name(products.get(0).getName());
					cartProductVO.setPrice(products.get(0).getPrice());
					cartProductVO.setStatus(products.get(0).getStatus());
					cartProductVO.setStock(products.get(0).getStock());
					cartProductVO.setSubtitle(products.get(0).getSubtitle());
					Long stock = products.get(0).getStock();
					Long limitProductCount=(long) 0;
					if(stock>=cart.getQuantity()) {
						//库存充足
						limitProductCount=cart.getQuantity();
						cartProductVO.setLimitQuantity("LIMIT_NUM_SUCCESS");
					}else {
						//库存不足
						limitProductCount=stock;
						//更新购物车中的商品的数量
						Long id = cart.getId();
						jdbcUtil.update(sql3, stock,id);
						cartProductVO.setLimitQuantity("LIMIT_NUM_FAIL");
					}
					cartProductVO.setQuantity(limitProductCount);
					
					cartProductVO.setTotal_price(bigDecimalUtil.mul(products.get(0).getPrice().doubleValue(), Double.valueOf(cartProductVO.getQuantity())));
				
					
				}
				System.out.println("这个商品check为"+cartProductVO.getChecked());
				if(cartProductVO.getChecked()==1){
				cartTotalPrice=bigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVO.getTotal_price().doubleValue());
				}
				
				cartProductVOList.add(cartProductVO);
			}
		}
		cartVO.setCartProductVOList(cartProductVOList);
		//3.计算总价格
		cartVO.setCartTotalPrice(cartTotalPrice);
		//4.判断购物车是否全选
		List<shoppingcart> checkedIsZero = jdbcUtil.select(shoppingcart.class, sql4, user_id);
		int i = checkedIsZero.size();
		if(i>0) {
			cartVO.setAllChecked(false);
		}else {
			cartVO.setAllChecked(true);
		}
		
		//5.返回结果
		return cartVO;
	}

    //购物车中的数量
	public ServerResponse get_cart_product_count(String userid) {
		// TODO Auto-generated method stub
		String sql="select * from shoppingcart where user_id=?";
		List<shoppingcart> list=jdbcUtil.select(shoppingcart.class, sql, userid);
		long shu=0;
		for(shoppingcart c:list) {
			shu+=c.getQuantity();
		}
		return ServerResponse.serverResponseBySuccess(shu,"data中存的是数量");
	}
    //全选
	public ServerResponse select_all(String userid) {
		// TODO Auto-generated method stub
		String sql="update shoppingcart set checked='1',update_time=? where user_id=?";
		Date date = new Date();
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String time=sdf.format(date);
		int i=jdbcUtil.update(sql, time,userid);
		long user_id=Long.parseLong(userid);
	    return ServerResponse.serverResponseBySuccess(getCartVO(user_id),"ok");
	}
    //取消全选
	public ServerResponse un_select_all(String userid) {
		// TODO Auto-generated method stub
		String sql="update shoppingcart set checked='0',update_time=? where user_id=?";
		Date date = new Date();
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String time=sdf.format(date);
		int i=jdbcUtil.update(sql, time,userid);
		long user_id=Long.parseLong(userid);
	    return ServerResponse.serverResponseBySuccess(getCartVO(user_id),"ok");
	}

}
